package com.liuqi.iot.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liuqi.iot.bean.dto.DeviceDataDTO;
import com.liuqi.iot.bean.dto.DeviceModelFieldDTO;
import com.liuqi.iot.bean.query.DeviceDataQuery;
import com.liuqi.iot.service.DeviceDataEntityService;
import com.liuqi.iot.service.DeviceModelPublishedEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 设备数据控制器 
 * @author Coder Generator 2025-03-22 15:29:32 
 **/
@RestController
@RequestMapping("/device-data")
@Slf4j
@Tag(name = "设备数据控制器")
public class DeviceDataController {
    @Autowired
    private DeviceDataEntityService service;

    @Autowired
    private DeviceModelPublishedEntityService publishedService;

    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<DeviceDataDTO> pageQuery(@RequestBody @Validated DeviceDataQuery query) {
        IPage<DeviceDataDTO> page = service.pageQuery(query);
        this.appendParamInfo(query.getDeviceCode(), page.getRecords());
        return page;
    }

    @PostMapping("query")
    @Operation(summary = "查询-不分页")
    public List<DeviceDataDTO> query(@RequestBody @Validated DeviceDataQuery query) {
        List<DeviceDataDTO> list = service.query(query);
        this.appendParamInfo(query.getDeviceCode(), list);
        return list;
    }

    private void appendParamInfo(String deviceCode, List<DeviceDataDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        // 补充参数相关信息
        Map<String, DeviceModelFieldDTO> fields = publishedService.getDeviceFields(deviceCode);
        list.forEach(dto -> {
            String param = dto.getParamCode();
            DeviceModelFieldDTO field = fields.get(param);
            if (null != field) {
                dto.setParamName(field.getName());
                dto.setUnit(field.getUnit());
                dto.setType(field.getType());
                dto.setDataType(field.getDataType());
            }
        });
    }
}